package com.baidu.manager.common.shiro;

import com.baidu.manager.common.utils.Result;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: jql
 * @description: TODO()
 * @Date: Created by 11:55 2018/4/20
 */
public class ShiroAuthenticatingFilter extends AuthenticatingFilter{

    //创建shrio认证的token
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //获取请求token
        String token = getRequestToken((HttpServletRequest) servletRequest);

        if (StringUtils.isBlank(token)){
            return null;

        }
        return new ShiroToken(token);
    }

    /**
     * 是否允许访问
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    //拒绝访问的出来
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) servletRequest);
        if (StringUtils.isBlank(token)){
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            String json = new Gson().toJson(Result.error(HttpStatus.SC_UNAUTHORIZED,"token失效"));
            response.getWriter().print(json);

            return false;
        }
        return executeLogin(servletRequest,servletResponse);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");

        try{
            //处理登录失败的异常
            Throwable throwable = e.getCause() ==null?e:e.getCause();
            Result r = Result.error(HttpStatus.SC_UNAUTHORIZED,throwable.getMessage());

            String json = new Gson().toJson(r);
            httpResponse.getWriter().print(json);
        }catch (IOException e1){

        }
        return false;
    }

    private String getRequestToken(HttpServletRequest request){
        //从header中获取token
        String token = request.getHeader("token");

        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        return token;
    }
}
